package org.destinyshine.cricket.connector.nio;

import org.destinyshine.cricket.connector.Connection;
import org.destinyshine.cricket.connector.ConnectionReceiver;
import org.destinyshine.cricket.connector.HttpServletResponseImpl;
import org.destinyshine.cricket.connector.ReuqestConsts;
import org.destinyshine.cricket.connector.nio.RequestParser;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * Created by destinyliu on 2016/2/20.
 */
public class SocketChannelConnectionHandler implements ReuqestConsts {

    private final SocketChannel channel;
    private ConnectionReceiver connectionReceiver;
    private RequestParser requestParser;

    public SocketChannelConnectionHandler(SocketChannel channel, ConnectionReceiver connectionReceiver) {
        this.channel = channel;
        this.connectionReceiver = connectionReceiver;
        this.requestParser = new RequestParser();
    }

    public void resolveByteBuffer(ByteBuffer byteBuffer) {
        this.requestParser.resolveByteBuffer(byteBuffer);
        if (requestParser.isRequestReady()) {
            try {
                channel.shutdownInput();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Connection connection = new Connection();
            connection.setRequest(this.requestParser.getRequest());
            connection.setResponse(new HttpServletResponseImpl(this.channel));
            this.connectionReceiver.recevieConnection(connection);
        }
    }
}
